package ua.at.tsvetkov.samizdat.activities;

import java.util.ArrayList;

import ua.at.tsvetkov.samizdat.Const;
import ua.at.tsvetkov.samizdat.R;
import ua.at.tsvetkov.samizdat.fragments.FrgBooks;
import ua.at.tsvetkov.samizdat.fragments.FrgGenres;
import ua.at.tsvetkov.samizdat.services.SrvUpdate;
import android.app.ActionBar;
import android.app.ActionBar.OnNavigationListener;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.SearchView;
import android.widget.SpinnerAdapter;

public class AcMainPhone extends Activity implements IMenuActivity {

	private FrgBooks			fragmentBooks;
	private FrgGenres			fragmentGenres;

	private Integer			currentGenresClickedPosition	= -1;
	private MenuItem			sortByBall;
	private MenuItem			sortByDate;
	private ProgressDialog	progressDialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ac_main_phone);

		IntentFilter intentFilter = new IntentFilter(Const.BROADCAST_MESSAGE);
		registerReceiver(intentReceiver, intentFilter);

		fragmentBooks = new FrgBooks();
		fragmentGenres = new FrgGenres();

		FragmentTransaction ft = getFragmentManager().beginTransaction();
		ft.add(R.id.activity_main_phone_parent_view, fragmentGenres);
		ft.commit();

		ActionBar actionBar = getActionBar();
		// actionBar.setDisplayHomeAsUpEnabled(true);
		actionBar.setDisplayShowTitleEnabled(false);
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
		ArrayList<String> objects = new ArrayList<String>();
		objects.add(Const.GENRES);
		objects.add(Const.AUTHOR);
		objects.add(Const.READ);
		objects.add(Const.DOWNLOADED);
		objects.add(Const.FAVORITES);

		SpinnerAdapter spinnerAdapter = new ArrayAdapter<String>(this, R.layout.ac_main_phone_action_bar_item, R.id.menu_item_text_view, objects);
		actionBar.setListNavigationCallbacks(spinnerAdapter, new OnNavigationListener() {
			@Override
			public boolean onNavigationItemSelected(int itemPosition, long itemId) {
				// TODO Auto-generated method stub
				return false;
			}
		});
	}

	@Override
	protected void onNewIntent(Intent intent) {

		// this intent send when we click to some genre
		// after this we change genres fragment to books fragment
		Integer clickedPositionGenres = intent.getIntExtra(Const.FRAGMENT_GENRES_CLICK_POSITION, -1);
		if (clickedPositionGenres != null && clickedPositionGenres != -1) {
			currentGenresClickedPosition = clickedPositionGenres;
			Bundle args = new Bundle();
			args.putInt(Const.FRAGMENT_GENRES_CLICK_POSITION, clickedPositionGenres);
			fragmentBooks.setArguments(args);
			FragmentTransaction ft = getFragmentManager().beginTransaction();
			ft.addToBackStack(Const.FRAGMENT_AUTHORS);
			ft.replace(R.id.activity_main_phone_parent_view, fragmentBooks);
			ft.commit();
			// showSortMenu();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main_activity_menu, menu);

		MenuItem settings = menu.findItem(R.id.main_menu_settings);
		MenuItem updateBooks = menu.findItem(R.id.main_menu_update);
		sortByBall = menu.findItem(R.id.main_menu_sort_by_ball);
		sortByDate = menu.findItem(R.id.main_menu_sort_by_date);
		SearchView searchView = (SearchView) menu.findItem(R.id.main_menu_search).getActionView();

		if (fragmentBooks.isVisible()) {
			showSortMenu();
		} else {
			hideSortMenu();
		}

		searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

			@Override
			public boolean onQueryTextSubmit(String query) {
				if (fragmentBooks.isVisible()) {
					fragmentBooks.getFragmentBooksAdapter().getFilter().filter(query);
				}
				return false;
			}

			@Override
			public boolean onQueryTextChange(String newText) {
				// if (fragmentGenres.isVisible()) {
				// fragmentGenres.getFragmentGenresAdapter().getFilter().filter(newText);
				// }
				return false;
			}
		});

		searchView.setOnCloseListener(new SearchView.OnCloseListener() {

			@Override
			public boolean onClose() {
				if (fragmentBooks.isVisible()) {
					fragmentBooks.getFragmentBooksAdapter().getFilter().filter("");
				}
				return false;
			}
		});

		settings.setOnMenuItemClickListener(new OnMenuItemClickListener() {

			@Override
			public boolean onMenuItemClick(MenuItem item) {
				startActivity(new Intent(AcMainPhone.this, PrefAcSamizdat.class));
				return false;
			}
		});

		updateBooks.setOnMenuItemClickListener(new OnMenuItemClickListener() {

			@Override
			public boolean onMenuItemClick(MenuItem arg0) {
				startService(new Intent(AcMainPhone.this, SrvUpdate.class));
				progressDialog = ProgressDialog.show(AcMainPhone.this, AcMainPhone.this.getString(R.string.UPDATING_BOOKS), AcMainPhone.this.getString(R.string.WAIT_FEW_SECONDS), true);
				return false;
			}
		});

		sortByBall.setOnMenuItemClickListener(new OnMenuItemClickListener() {

			@Override
			public boolean onMenuItemClick(MenuItem item) {
				sortByBall.setChecked(!sortByBall.isChecked());

				if (sortByBall.isChecked() && sortByDate.isChecked()) {
					fragmentBooks.getFragmentBooksAdapter().refreshListViewWithIdAndSortOrder(currentGenresClickedPosition, Const.BALL + " desc" + ", " + Const.DATE + " desc");
				}
				if (!sortByBall.isChecked() && sortByDate.isChecked()) {
					fragmentBooks.getFragmentBooksAdapter().refreshListViewWithIdAndSortOrder(currentGenresClickedPosition, Const.DATE + " desc");
				}
				if (sortByBall.isChecked() && !sortByDate.isChecked()) {
					fragmentBooks.getFragmentBooksAdapter().refreshListViewWithIdAndSortOrder(currentGenresClickedPosition, Const.BALL + " desc");
				}
				if (!sortByBall.isChecked() && !sortByDate.isChecked()) {
					fragmentBooks.getFragmentBooksAdapter().refreshListViewWithIdAndSortOrder(currentGenresClickedPosition, null);
				}
				return false;
			}
		});

		sortByDate.setOnMenuItemClickListener(new OnMenuItemClickListener() {

			@Override
			public boolean onMenuItemClick(MenuItem item) {

				sortByDate.setChecked(!sortByBall.isChecked());

				if (sortByBall.isChecked() && sortByDate.isChecked()) {
					fragmentBooks.getFragmentBooksAdapter().refreshListViewWithIdAndSortOrder(currentGenresClickedPosition, Const.BALL + " desc" + ", " + Const.DATE + " desc");
				}
				if (!sortByBall.isChecked() && sortByDate.isChecked()) {
					fragmentBooks.getFragmentBooksAdapter().refreshListViewWithIdAndSortOrder(currentGenresClickedPosition, Const.DATE + " desc");
				}
				if (sortByBall.isChecked() && !sortByDate.isChecked()) {
					fragmentBooks.getFragmentBooksAdapter().refreshListViewWithIdAndSortOrder(currentGenresClickedPosition, Const.BALL + " desc");
				}
				if (!sortByBall.isChecked() && !sortByDate.isChecked()) {
					fragmentBooks.getFragmentBooksAdapter().refreshListViewWithIdAndSortOrder(currentGenresClickedPosition, null);
				}
				return false;
			}
		});

		return true;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(intentReceiver);
	}

	public void hideSortMenu() {
		sortByBall.setVisible(false);
		sortByDate.setVisible(false);
		sortByBall.setChecked(false);
		sortByDate.setChecked(false);
	}

	public void showSortMenu() {
		sortByBall.setVisible(true);
		sortByDate.setVisible(true);
	}

	BroadcastReceiver	intentReceiver	= new BroadcastReceiver() {
													@Override
													public void onReceive(Context context, Intent intent) {
														String serviceUpdateStoped = intent.getStringExtra(Const.SERVICE_UPDATE_STOPED);
														Integer loadingPercents = intent.getIntExtra(Const.UPDATE_LOADING_PERCENTS, -1);

														if(loadingPercents != -1){
															progressDialog.setMessage(AcMainPhone.this.getString(R.string.WAIT_FEW_SECONDS) + " " + String.valueOf(loadingPercents) + "%");
														}
														if (serviceUpdateStoped != null && serviceUpdateStoped.equals(Const.SERVICE_UPDATE_STOPED)) {
															progressDialog.dismiss();
															progressDialog.cancel();
														}
													}
												};
}
